package master.system.function;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import master.common.data.TreeJSON;
import master.common.json.JSONResponseObject;
import master.common.pk.LongTimePKGenerator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
 */
@Controller
@RequestMapping("/functions")
public class FunctionController {

	private static Log log = LogFactory.getLog(FunctionController.class);

	@Autowired
	FunctionService functionService;

	/**
     * 获取所有模块
	 * @return
	 */
	@RequestMapping("/management.do")
	@ResponseBody
	public String management() {
		return getAllModules();
	}

	/**
	 * 获取所有模块
	 * @return
	 */
	@RequestMapping("/module_list.do")
	@ResponseBody 
	public String getAllModules() {
		List<Module> modules = functionService.getAllModules();
		return TreeJSON.fromListOfObject(modules).toJSONString();
	}

	/**
	 * 保存模块
	 * @param module
	 * @param result
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/save_module.do")
	@ResponseBody
	public String saveModule(@ModelAttribute("module") @Valid Module module, 
			BindingResult result, HttpServletResponse response) {
		try {
//			if (result.hasErrors()) {  
//				JSONResponseObject failure = JSONResponseObject.newFailureJSONResponseObject();
//				failure.setValue("模块校验失败");
//				return failure.toJSONString();  
//		    }  
		  
			boolean isNew = module.getId() == 0L;
			if(isNew) { 
				module.setId(LongTimePKGenerator.getInstance().nextLongId());
			}
			
			if(!StringUtils.hasText(module.getIcon()))
				module.setIcon("images/class.gif");
			
			functionService.saveModule(module);
			
			
			JSONObject json = new JSONObject();
			json.put("success", true);
			json.put("value", "保存模块成功");
			json.put("id", String.valueOf(module.getId()));
			json.put("name", module.getName());
			json.put("icon", module.getIcon());
			json.put("description", module.getDescription());
			json.put("isnew", isNew? true: false);
			return json.toJSONString();
			
		} catch (Throwable th) {
			log.error("保存模块出错", th);
			JSONResponseObject failure = JSONResponseObject.newFailureJSONResponseObject();
			failure.setValue("保存模块出错");
			return failure.toJSONString();
		}
	}
	
	/**
	 * 获取模块描述
	 * @param id
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/get_module_description.do")
	@ResponseBody 
	public String getModuleDescription(
			@RequestParam(value="id", required=true) long id, Model model) {
		Map<String, Object> module = functionService.getModule(id);

		JSONObject json = new JSONObject();
		json.put("description", (module.get("description") != null)? 
				module.get("description"): "");
		
		return json.toJSONString();
	}
	
	/**
	 * 获取模块
	 * @param id
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/get_module.do")
	@ResponseBody 
	public String getModule(
			@RequestParam(value="id", required=true) long id, Model model) {
		Map<String, Object> module = functionService.getModule(id);

		JSONObject functionJsonObject = new JSONObject();
		functionJsonObject.put("id", String.valueOf(module.get("id")));
		functionJsonObject.put("parentId", String.valueOf(module.get("parent_id")));
		functionJsonObject.put("name", module.get("name"));
		functionJsonObject.put("description", module.get("description"));
		functionJsonObject.put("url", module.get("url"));
		functionJsonObject.put("priority", module.get("priority"));
		functionJsonObject.put("icon", module.get("icon"));

		JSONArray array = new JSONArray();
		array.add(functionJsonObject);

		JSONObject json = new JSONObject();
		json.put("resultSet", array);
		return json.toJSONString();
	}
	
	/**
	 * 删除模块成功
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/delete_module.do")
	@ResponseBody 
	public String deleteModule(
			@RequestParam(value="id", required=true) long id, Model model) {
		try {
			functionService.deleteModule(id);
			JSONResponseObject success = JSONResponseObject.newSuccessJSONResponseObject();
			success.setValue("删除模块成功");
			return success.toJSONString();
		}catch(Throwable th) {
			log.error("模块删除出错", th);
			JSONResponseObject failure = JSONResponseObject.newFailureJSONResponseObject();
			failure.setValue("删除模块出错");
			return failure.toJSONString();
		}
	}
	
	/**
	 * 根据模块获取功能列表
	 * @param moduleId
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/function_list.do")
	@ResponseBody 
	public String getFunctionsByModuleId(
			@RequestParam(value="moduleId", required=false) long moduleId, Model model) {
		List<Function> functions = functionService.getFunctionsByModuleId(moduleId);
		JSONObject json = new JSONObject();
		json.put("totalCount", functions.size());
 
		JSONArray array = new JSONArray();
		for(Function function : functions) {
			JSONObject funcj = new JSONObject();
			funcj.put("functionId", String.valueOf(function.getId()));
			funcj.put("moduleId", String.valueOf(function.getModuleId()));
			funcj.put("name", function.getName());
			funcj.put("description", function.getDescription());
			funcj.put("ismanager", true);
			array.add(funcj);
		}
		json.put("resultSet", array);
		return json.toJSONString();
	}

	/**
	 * 保存功能信息
	 * @param func
	 * @param response
	 */
	@RequestMapping(value="/save_function.do")
	@ResponseBody
	public String saveFunction(@ModelAttribute("function") @Valid Function func, 
			BindingResult result, HttpServletResponse response) {
		try {
			if (result.hasErrors()) {//如果校验失败了  
				JSONResponseObject failure = JSONResponseObject.newFailureJSONResponseObject();
				failure.setValue("功能校验失败");
				return failure.toJSONString();  
		    }  
		  
			boolean isNew = func.getId() == 0L;
			if(isNew) {
				func.setId(LongTimePKGenerator.getInstance().nextLongId());
			}

			functionService.saveFunction(func);
			
			JSONResponseObject success = JSONResponseObject.newSuccessJSONResponseObject();
			success.setValue("保存功能成功");
			return success.toJSONString();
			
		} catch (Throwable th) {
			log.error("保存功能出错", th);
			JSONResponseObject failure = JSONResponseObject.newFailureJSONResponseObject();
			failure.setValue("保存功能出错");
			return failure.toJSONString();
		}
	}

	/**
	 * 获取指定功能
	 * @param id
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/get_function.do")
	@ResponseBody 
	public String getFunction(
			@RequestParam(value="id", required=true) long id, Model model) {
		Map<String, Object> function = functionService.getFunction(id);

		JSONObject functionJsonObject = new JSONObject();
		functionJsonObject.put("id", function.get("id"));
		functionJsonObject.put("moduleId", function.get("module_id"));
		functionJsonObject.put("name", function.get("name"));
		functionJsonObject.put("description", function.get("description"));
		functionJsonObject.put("url", function.get("url"));
		functionJsonObject.put("priority", function.get("priority"));
		functionJsonObject.put("icon", function.get("icon"));

		JSONArray array = new JSONArray();
		array.add(functionJsonObject);

		JSONObject json = new JSONObject();
		json.put("resultSet", array);
		return json.toJSONString();
	}
	
	/**
	 * 删除功能
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/delete_function.do")
	@ResponseBody 
	public String deleteFunction(
			@RequestParam(value="id", required=true) long id, Model model) {
		try {
			functionService.deleteFunction(id);
			JSONResponseObject success = JSONResponseObject.newSuccessJSONResponseObject();
			success.setValue("删除功能成功");
			return success.toJSONString();
		}catch(Throwable th) {
			log.error("功能删除出错", th);
			JSONResponseObject failure = JSONResponseObject.newFailureJSONResponseObject();
			failure.setValue("删除功能出错");
			return failure.toJSONString();
		}
	}
}